import { defineStore } from 'pinia'

export interface Doll {
  id: string
  name: string
  avatar: string
  color: string
  isPinned?: boolean
}

export const useDollsStore = defineStore('dolls', {
  state: () => ({
    dolls: [
      {
        id: '1',
        name: '小布',
        avatar: 'https://api.dicebear.com/7.x/adventurer/svg?seed=doll1',
        color: '#60a5fa',
        isPinned: false,
      },
      {
        id: '2',
        name: '贝贝',
        avatar: 'https://api.dicebear.com/7.x/adventurer/svg?seed=doll2',
        color: '#f472b6',
        isPinned: false,
      },
      {
        id: '3',
        name: '暖暖',
        avatar: 'https://api.dicebear.com/7.x/adventurer/svg?seed=doll3',
        color: '#fb923c',
        isPinned: false,
      },
    ] as Doll[],
    activeDollId: '1',
  }),

  getters: {
    sortedDolls: (state) => {
      return [...state.dolls].sort((a, b) => {
        if (a.isPinned === b.isPinned) return 0
        return a.isPinned ? -1 : 1
      })
    },

    visibleDolls: (state) => {
      return state.sortedDolls.slice(0, 3)
    },

    currentDoll: (state) => {
      return state.dolls.find((doll) => doll.id === state.activeDollId)
    },
  },

  actions: {
    setActiveDoll(id: string) {
      this.activeDollId = id
    },

    addDoll(doll: Omit<Doll, 'id'>) {
      const newDoll = {
        ...doll,
        id: Date.now().toString(),
      }
      this.dolls.push(newDoll)
      return newDoll
    },

    updateDoll(id: string, updates: Partial<Doll>) {
      const index = this.dolls.findIndex((d) => d.id === id)
      if (index > -1) {
        this.dolls[index] = { ...this.dolls[index], ...updates }
      }
    },

    deleteDoll(id: string) {
      const index = this.dolls.findIndex((d) => d.id === id)
      if (index > -1) {
        this.dolls.splice(index, 1)
        // 如果删除的是当前选中的娃娃，选中第一个娃娃
        if (this.activeDollId === id) {
          this.activeDollId = this.dolls[0]?.id || ''
        }
      }
    },

    togglePin(id: string) {
      const doll = this.dolls.find((d) => d.id === id)
      if (doll) {
        doll.isPinned = !doll.isPinned
        // 重新排序
        this.dolls.sort((a, b) => {
          if (a.isPinned === b.isPinned) return 0
          return a.isPinned ? -1 : 1
        })
      }
    },
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'memory-dolls',
        storage: localStorage,
      },
    ],
  },
})
